package servlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author 黄衡熙
 * @version 1.0
 */
@WebServlet("/deleteById")
public class DeleteEmpServlet extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        String id=req.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "qq670892");
            String sql = "delete from t_emp where id=?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, Integer.parseInt(id));
            ps.executeUpdate();
            resp.sendRedirect("findAll");
        } catch (Exception e) {
            out.println("<h1 style='color:red;'>对不起,删除失败,失败原因:" + e.getMessage() + "</h1>");
        }finally {
            if(conn !=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放异常");
                }
            }
            if(ps !=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放异常");
                }
            }
        }

    }
}
